package com.dylan.历史.多线程.并发编程的艺术.编程基础.模拟连接池;

import com.dylan.历史.util.LogUtil;

/**
 * Created by Dylan on 2018/9/18.
 */
public class ConnectionPoolTest {

    static volatile ConnectionPool pool = new ConnectionPool(10);

    public static void main(String[] args) {
        for (int i = 0; i < 40; i++) {
            new Thread(() -> {
                try {
                    long start = System.currentTimeMillis();
                    Connection connection = pool.fetch(400);
                    long end = System.currentTimeMillis();
                    if (connection == null) {
                        LogUtil.info("获取连接失败");
                    } else {
                        LogUtil.info("获取到的连接为：" + connection.getName() + "。耗时：" + (end - start) + "ms");
                        connection.execute();
                        pool.release(connection);
                        LogUtil.info("----- 释放连接：" + connection.getName());
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
